package main

import (
	"fmt"
	"github.com/gorilla/mux"
	"net/http"
)

func main() {
	r := mux.NewRouter()
	//1 路径变量
	r.HandleFunc("/books/{title}/page/{page}",
		func(w http.ResponseWriter, r *http.Request) {
			vars := mux.Vars(r)
			title := vars["title"]
			page := vars["page"]
			fmt.Fprintf(w, "You've requested the book: %s on page %s\n", title, page)
		})

	//2 Restful 请求方法路由
	testRest(r)

	//3 hostname路由
	r.HandleFunc("/books/mybookstore/{title}", ReadBook).Host("www.mybookstore.com")

	//4 http 与 https
	//r.HandleFunc("/secure", SecureHandler).Schemes("https")
	//r.HandleFunc("/insecure", InsecureHandler).Schemes("http")

	//5 子路由
	testChildRoute(r)

	//第二个参数需把上面的路由对象放入
	http.ListenAndServe(":8989", r)
}

func testChildRoute(r *mux.Router) {
	subrouter := r.PathPrefix("/reader").Subrouter()
	subrouter.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		fmt.Fprintf(writer, "Read root")
	})
	subrouter.HandleFunc("/count", func(writer http.ResponseWriter, request *http.Request) {
		fmt.Fprintf(writer, "Read Count")
	})

}

func testRest(r *mux.Router) {
	// curl -X POST http://localhost:8989/books/b1
	r.HandleFunc("/books/{title}", CreateBook).Methods("POST")

	// curl -X GET http://localhost:8989/books/b1
	r.HandleFunc("/books/{title}", ReadBook).Methods("GET")

	// curl -X PUT http://localhost:8989/books/b1
	r.HandleFunc("/books/{title}", UpdateBook).Methods("PUT")

	// curl -X DELETE http://localhost:8989/books/b1
	r.HandleFunc("/books/{title}", DeleteBook).Methods("DELETE")

}

func DeleteBook(writer http.ResponseWriter, request *http.Request) {
	vars := mux.Vars(request)
	fmt.Fprintf(writer, "Delete %s", vars["title"])
}

func UpdateBook(writer http.ResponseWriter, request *http.Request) {
	vars := mux.Vars(request)
	fmt.Fprintf(writer, "Update %s", vars["title"])
}

func ReadBook(writer http.ResponseWriter, request *http.Request) {
	vars := mux.Vars(request)
	fmt.Fprintf(writer, "Read %s", vars["title"])
}

func CreateBook(writer http.ResponseWriter, request *http.Request) {
	vars := mux.Vars(request)
	fmt.Fprintf(writer, "Create %s", vars["title"])
}
